// pages/hudong/hudong.js
var utils = require('../../utils/api.js');
var base64 = require('../../utils/base64.js');
var md5 = require('../../utils/md5.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tipshow: false,
    qr1show: false,
    qr2show: false,
    wanshangisShow: false,
    timingRotation: 2000, //定时轮询时间
    moroCoin: 0, //魔彩币
    advertisingList: [], //广告  '../../assets/banner.png',
    goodsList: [], //互动商品
    goodsIndexList: [], //页面显示
    indicatorDots: true,
    autoplay: true,
    interval: 2000,
    duration: 1000,
    picurl: '../../assets/logo.png',
    allLoading: false, //加载判断
    listType: 0, //商品类型
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    this.setData({
      tipshow: false,
      qr1show: false,
      qr2show: false,
      wanshangisShow: false,
      listType: 0,
      allLoading: false,
    })
    wx.showLoading({
      title: '加载中',
    })
    that.interActionReq()
    // setTimeout(function () {
      
    // }, that.data.timingRotation)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 商品列表按键点击
   */
  btntip: function (res) {
    var that = this
    let type = res.currentTarget.dataset.type //获取属性type
    that.setData({ listType: type })
    if (type == 1) {
      let id = res.currentTarget.dataset.id //获取属性id
      var index = that.findElem(that.data.goodsList, "id", id)
      that.setData({ goodsIndexList: that.data.goodsList[index] })
      that.addressReq(id, type)
      that.setData({ qr1show: true })
    } else if (type == 2) { //类型2 实物
      let id = res.currentTarget.dataset.id //获取属性id
      var index = that.findElem(that.data.goodsList, "id", id)
      that.setData({ goodsIndexList: that.data.goodsList[index] })
      that.addressReq(id, type)
      that.setData({ qr2show: true })
    } else if (type == 3) {
      let id = res.currentTarget.dataset.id //获取属性id
      wx.navigateTo({
        url: '/pages/choujiang/choujiang?id=' + id + '&goodsTypeId=' + type
      })
    }
  },
  addressReq: function (id, goodsTypeId) { //地址请求
    var that = this
    // console.log(wx.getStorageSync('serverSessionKey'))
    // if(!wx.getStorageSync('serverSessionKey')){
    //   getApp().userLogin()
    // }
    wx.request({
      url: getApp().globalData.requestUrl + '/getReceiptInformation',
      method: "post",
      data: {
        paramList: base64.CusBASE64.encoder('{"serverSessionKey":"' + wx.getStorageSync('serverSessionKey') + '","id":"' + id + '","goodsTypeId":"' + goodsTypeId + '"}')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        if (res.statusCode == 200) { //判断wx.request请求是否成功
          if (res.data) {
            var dat = utils.stringToJson(utils.ascii2native(res.data))
            console.log('interface:getReceiptInformation')
            console.log(dat)
            if (dat.status == 0) {
              if (dat.dataList) {
                that.setData({
                  'goodsIndexList.Address': dat.dataList.Address, //联系地址
                  'goodsIndexList.contactName': dat.dataList.contactName, //联系人                  
                  'goodsIndexList.phoneNumber': dat.dataList.phoneNumber, //电话
                })
              } else { //获取信息错误
                that.CommonShowMsg('数据错误', 'address', goodsTypeId)
              }
            } else {
              that.CommonShowMsg(dat.errorMsg, 'address', goodsTypeId)
            }
          } else {//服务器没有返回数据
            that.CommonShowMsg('数据错误', 'address', goodsTypeId)
          }
        } else {//请求失败
          that.CommonShowMsg('数据错误', 'address', goodsTypeId)
        }
      },
      fail: function (res) {
      },
      complete: function () {
      },
    })
  },
  findElem: function (arrayToSearch, attr, val) {
    for (var i = 0; i < arrayToSearch.length; i++) {
      if (arrayToSearch[i][attr] == val) {
        return i;
      }
    }
    return -1;
  },
  chongzhi: function () {
    this.setData({
      qr1show: false,
      tipshow: true
    })
  },
  goumai: function () {
    var that = this
    if (that.data.moroCoin < parseInt(that.data.goodsIndexList.goodsPrice)) {
      wx.showToast({
        title: '魔彩币不足',
        icon: 'none',
        duration: 3000,
      })
      return
    }
    if (that.data.listType == 2) {

      if (!that.data.goodsIndexList.phoneNumber || !that.data.goodsIndexList.Address || !that.data.goodsIndexList.contactName) {
        wx.showToast({
          title: '信息不全',
          icon: 'none',
          duration: 3000,
        })
        return
      }
    }

    wx.showModal({
      title: '提示',
      content: '您是否要兑换',
      success: function (res) {
        if (res.confirm) {
          // 购买
          that.orderCreateReq();
        } else if (res.cancel) {
        }
      }
    })
    return
    wx.navigateTo({
      url: '/pages/dingdanxiangqing/dingdanxiangqing'
    })
  },
  tipbgtap: function () {
    this.setData({
      tipshow: false,
      qr1show: false,
      qr2show: false,
      wanshangisShow: false
    })
  },
  interActionReq: function () { // 互动请求
    var that = this
    console.log(wx.getStorageSync('serverSessionKey'))
    if (wx.getStorageSync('serverSessionKey')) {
      wx.request({
        url: getApp().globalData.requestUrl + '/interaction',
        method: "post",
        data: {
          paramList: base64.CusBASE64.encoder('{"serverSessionKey":"' + wx.getStorageSync('serverSessionKey') + '"}')
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          if (res.statusCode == 200) { // 判断wx.request请求是否成功
            if (res.data) {
              that.setData({ allLoading: true })
              var dat = utils.stringToJson(utils.ascii2native(res.data))
              console.log('interface:interaction')
              console.log(dat)
              if (dat.status == 0) {
                if (dat.dataList) {
                  wx.hideLoading()
                  that.setData({
                    moroCoin: dat.dataList.moroCoin, //魔彩币赋值
                    advertisingList: dat.dataList.advertisingList.length != 0 ? dat.dataList.advertisingList : ['../../assets/banner.png'], //广告
                    goodsList: dat.dataList.goodsList, //商品
                    indicatorDots: dat.dataList.advertisingList.length != 0 ? true : false,
                  })
                  if (that.data.goodsList.length == 0) {
                    wx.showLoading({
                      title: '无商品信息',
                    })
                  }
                } else { //获取信息错误
                }
              } else {
                if (dat.errorMsg == 'open_id为空') {
                  console.log('open_id为空')
                  wx.login({
                    success: function (res) {
                      if (res.code) {
                        //发起网络请求拿serverSessionKey
                        getApp().userLogin(res)
                      } else {
                        console.log('获取用户登录态失败！' + res.errMsg)
                      }
                    }
                  })
                  that.interActionReq()
                }
              }
            } else {//服务器没有返回数据
              wx.showLoading({
                title: '获取数据失败',
                mask: true,
              })
            }
          } else {//请求失败
            wx.showLoading({
              title: '数据错误',
            })
          }
        },
        fail: function (res) {
        },
        complete: function () {
        }
      })
    } else {
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求拿serverSessionKey
            getApp().userLogin(res)
          } else {
            console.log('获取用户登录态失败！' + res.errMsg)
          }
        }
      })
      that.interActionReq()
      // wx.showLoading({
      //   title: '数据错误',
      //   // mask: true,
      // })
    }
  },
  /**
   * 订单提交req
   */
  orderCreateReq: function () {
    var that = this
    console.log('{"id":"' + that.data.goodsIndexList.id + '","serverSessionKey":"' + wx.getStorageSync('serverSessionKey') + '","goodsName":"' + that.data.goodsIndexList.goodsName + '","goodsCount":"1","goodsPrice":"' + that.data.goodsIndexList.goodsPrice + '","phoneNumber":"' + that.data.goodsIndexList.phoneNumber + '","contactName":"' + that.data.goodsIndexList.contactName + '","address":"' + that.data.goodsIndexList.Address + '"}')
    wx.request({
      url: getApp().globalData.requestUrl + '/placeOrder',
      method: "post",
      data: {
        paramList: base64.CusBASE64.encoder('{"id":"' + that.data.goodsIndexList.id + '","serverSessionKey":"' + wx.getStorageSync('serverSessionKey') + '","goodsName":"' + that.data.goodsIndexList.goodsName + '","goodsCount":"1","goodsPrice":"' + that.data.goodsIndexList.goodsPrice + '","phoneNumber":"' + that.data.goodsIndexList.phoneNumber + '","contactName":"' + that.data.goodsIndexList.contactName + '","address":"' + that.data.goodsIndexList.Address + '"}')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        if (res.statusCode == 200) { //判断wx.request请求是否成功
          if (res.data) {
            var dat = utils.stringToJson(utils.ascii2native(res.data))
            console.log('interface:placeOrder')
            console.log(dat)
            if (dat.status == 0) {
              if (that.data.listType == 1) {
                that.setData({
                  tipshow: true,
                  qr1show: false,
                  moroCoin: that.data.moroCoin - parseInt(that.data.goodsIndexList.goodsPrice),
                })
                // that.CommonShowMsg('兑换成功', 'address', that.data.listType)
              } else if (that.data.listType == 2) {
                that.setData({
                  tipshow: true,
                  qr2show: false,
                  moroCoin: that.data.moroCoin - parseInt(that.data.goodsIndexList.goodsPrice),
                })
                // that.CommonShowMsg('兑换成功', 'address', that.data.listType)
              }
            } else {
              that.CommonShowMsg(dat.errorMsg, 'address', that.data.listType)
            }
          } else {//服务器没有返回数据
            that.CommonShowMsg('数据错误', 'address', that.data.listType)
          }
        } else {//请求失败
          that.CommonShowMsg('数据错误', 'address', that.data.listType)
        }
      },
      fail: function (res) {
      },
      complete: function () {
      },
    })
  },
  /**
   * 互动商城公用错误信息
   */
  CommonShowMsg: function (msg, subtype, typeid) {
    var that = this
    wx.showToast({
      title: msg,
      mask: true,
      icon: 'none',
      duration: 3000,
    })
    if (subtype == 'address') {
      if (typeid == 1) {
        this.setData({ qr1show: false })
      } else if (typeid == 2) {
        that.setData({ qr2show: false })
      } else if (typeid == 3) {
      }
    } else if (subtype == 'reqlist') {
    }
  },
})